
const App = getApp()
Page({
  // ChatGPT
  /**
  * 页面的初始数据
  */

  data: {
    newslist: [{
      direction: 'left',
      text: '你好，有什么需要我帮助的吗？'
    }],
    userInfo: {},
    scrollTop: 0,
    increase: false,//图片添加区域隐藏
    aniStyle: true,//动画效果
    message: "",
    conversationId: '',
    messageId: '',
    canInput: false,
    navBarHeight: ''
  },

  copyTip (e) {
    wx.setClipboardData({
      data: e.currentTarget.dataset.content,
      success: function () {
        wx.showToast({
          title: '复制成功',
          icon: 'none',
          mask: 'true'
        })
      }
    })
  },

  /**
  * 生命周期函数--监听页面加载
  */

  onLoad: function () {
    this.setData({
      userInfo: wx.getStorageSync('userInfo'),
      navBarHeight: App.globalData.navHeight
    })
    console.log(this.data.navBarHeight, 'navBarHeight')
  },

  // 页面卸载

  onUnload () {

  },


  //监听input值的改变

  bindChange (res) {
    this.setData({
      message: res.detail.value
    })
  },

  cleanInput () {
    //button会自动清空，所以不能再次清空而是应该给他设置目前的input值
    this.setData({
      message: this.data.message
    })

  },

  increase () {
    this.setData({
      increase: true,
      aniStyle: true

    })

  },

  //点击空白隐藏message下选框
  outbtn () {
    this.setData({
      increase: false,
      aniStyle: true
    })
  },

  async send (e) {
    const _this = this
    if (this.data.message.trim() == "") {
      wx.showToast({
        title: '消息不能为空哦~',
        icon: "none",
        duration: 2000
      })
    } else {
      // 提问
      const params = {
        direction: 'right',
        text: _this.data.message
      }
      _this.data.newslist.push(params)
      _this.setData({
        newslist: _this.data.newslist,
        massage: ''
      })
      // 回答
      const res = await _this.sendMessage();
      this.setData({
        conversationId: res.conversationId,
        messageId: res.messageId
      })
      const ans = {
        direction: 'left',
        text: res.response
      }
      _this.data.newslist.push(ans)
      _this.setData({
        newslist: _this.data.newslist,
      })
    }
  },


  // 请求chat
  sendMessage () {
    const _this = this
    this.setData({
      canInput: true
    })
    const data = JSON.stringify({
      "questions": this.data.message,
      "conversationId": this.data.conversationId, //第一次会话可以不填
      "parentMessageId": this.data.parentMessageId //第一次会话可以不填
    });
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'https://api-tinystar.meinenghua.com/api/v1/chat/completions',
        header: {
          'App-Key': '9U6mgNwWxzlince-CM7w2',
          'App-Secret': 'sk-cawityeTxblaRpnC2FLDfIK1zmOIG',
          'Content-Type': 'application/json'
        },
        data: data,
        method: "post",
        success (data) {
          _this.setData({
            canInput: false
          })
          if (data.statusCode == 200) {
            resolve(data.data)
          }
        },
      });
    })
  }
})